package groovyhelper;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiFile;
import com.intellij.lang.Commenter;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public abstract class GroovyBaseOverrideAction extends AnAction {
    private AnAction delegateAction;

    public void setDelegate(AnAction delegateAction) {
        this.delegateAction = delegateAction;
    }

    public void actionPerformed(AnActionEvent anactionevent) {
        Project project = (Project) anactionevent.getDataContext().getData(DataConstants.PROJECT);
        PsiFile psiFile = (PsiFile) anactionevent.getDataContext().getData(DataConstants.PSI_FILE);
        if (psiFile != null) {
            String name = psiFile.getName();
            if (name != null && name.endsWith(".groovy")) {
                Editor editor = (Editor) anactionevent.getDataContext().getData(DataConstants.EDITOR);
                if (editor != null) {
                    groovyActionPerformed(anactionevent, editor, project, psiFile);
                    return;
                }
            }
        }
        if (delegateAction != null) {
            delegateAction.actionPerformed(anactionevent);
        }
    }

    abstract void groovyActionPerformed(AnActionEvent anActionEvent, Editor editor, Project project, PsiFile psiFile);

    protected void substitute(final Editor editor, final int startOffset, final int endOffset, final String replaceString, Project project, final int cursorOffset) {
            final Runnable runnable = new Runnable() {
                public void run() {
                    Document document = editor.getDocument();
                    document.replaceString(startOffset, endOffset, replaceString);
                    int moveOffset = replaceString.length() - endOffset + startOffset;
                    editor.getCaretModel().moveToOffset(endOffset + moveOffset + cursorOffset);
                }

            };

            CommandProcessor.getInstance().executeCommand(project,
                    new Runnable() {
                        public void run() {
                            ApplicationManager.getApplication().runWriteAction(runnable);
                        }
                    }, "GroovyTextReplacement", null);
        }

}
